package com.cmb.lk50.utils;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author       : 蒋俊钊 80256973
 * Date         : 2020/8/25
 * Copyright    (C) ChinaMerchantsBank
 */
public class GsonUtil {

    public static Map<String, Object> toMap(JsonObject jsonObject) {
        HashMap<String, Object> map = new HashMap<>();
        for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
            String key = entry.getKey();
            JsonElement value = entry.getValue();
            if (value instanceof JsonArray) {
                map.put(key, toList((JsonArray) value));
            } else if (value instanceof JsonObject) {
                map.put(key, toMap((JsonObject) value));
            } else {
                map.put(key, value);
            }
        }
        return map;
    }

    public static List<Object> toList(JsonArray jsonArray) {
        ArrayList<Object> list = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JsonElement value = jsonArray.get(i);
            if (value instanceof JsonArray) {
                list.add(toList((JsonArray) value));
            } else if (value instanceof JsonObject) {
                list.add(toMap((JsonObject) value));
            } else {
                list.add(value);
            }
        }
        return list;
    }
}
